var Fiber = require('fibers');;
(function() {

    var tld = require('tldjs');
    // var white_list_map = {};
    // white_list.forEach(function(origin) {
    //  white_list_map[origin] = true;
    // });
    var url = require("url");
    var domain = require("domain");
    var DomainCon = require("../core/domain/_con");
    var db = require("../core/db/index");
    var config = require("../core/_include/config");
    var domain_config_list = db.find_all(config.dbname.domain);

    //从数据库数据中生成白名单对象
    var white_list_map = {};

    function _domainConfig_to_whiteList(domain_config, index) {
        if (domain_config) {
            if (domain_config.is_secondary_domain) {
                white_list_map[domain_config.domain + ".dotnar.com" + (domain_config.port != 80 ? (":" + domain_config.port) : "")] = domain_config.bus_id
            } else {
                white_list_map[domain_config.domain] = domain_config.bus_id;
                if (tld.getSubdomain(domain_config.domain) == "") { //如果没有二级域名，自动加上www
                    white_list_map["www." + domain_config.domain] = domain_config.bus_id;
                }
            }
        } else {
            if ((parseInt(index) > -1)) {
                domain_config_list.splice(index, 1);
            }
        }
    };
    domain_config_list.forEach(_domainConfig_to_whiteList);
    //监听数据库改动，动态添加白名单
    db.on("insert", function(dbname, obj) {
        if (dbname === config.dbname.domain /*&&!(obj instanceof Array)不是数据库批量录入时触发的*/ ) {
            console.log("动态添加白名单对象：", obj);
            _domainConfig_to_whiteList(obj);
        }
    });

    //如果是数据库配置信息为空，将json文件的配置导入，否则直接使用数据库数据
    if (!domain_config_list.length) {
        var d = domain.create();
        d.on("error", function(e) {
            console.error("DOMAIN ERROR:", e);
        });
        //跨域调取的白名单
        var site_config = require("../origin").site_config;
        console.log("site_config:", site_config)
        for (var site in site_config) {
            // console.log(site);
            var site_domain = tld.getDomain(site);
            is_secondary_domain = site_domain === "dotnar.com";
            d.run(function() {
                Fiber(function() {
                    new DomainCon({
                        bus_id: site_config[site],
                        domain: is_secondary_domain ? tld.getSubdomain(site) : site_domain,
                        port: DomainCon.getPort(site),
                        is_secondary_domain: is_secondary_domain
                    });
                }).run();
            });
        }
    }

    module.exports = function(req, res, next) {
        var referer = req.header("referer") || "";
        http_header = referer.indexOf("https://") === 0 ? "https://" : "http://"
        var host = referer.replace(http_header, "").split("/")[0];
        if (host) {
            var origin = http_header + host;
        } else {
            origin = req.header("origin") || "";
            host = origin.replace(http_header, "");
        }
        var domain = tld.getDomain(origin) || "";
        req.headers["origin"] = origin;
        req.headers["host"] = host;
        req.headers["domain"] = domain;
        req.headers["protocol"] = http_header.replace("//", "");
        var user_ip_list = req.headers["user_ip_list"] = req.headers["x-forwarded-for"] || req.headers["x-remote-ip"] || req.ip;
        req.headers["user_ip"] = user_ip_list.split(",")[0];
        origin || (origin = "");
        host || (host = "");

        var origin_result = "http://www.datnor.com";
        console.log("domain, host, origin :", domain, host, origin);
        if (origin.indexOf("http://localhost:") === 0 || origin.indexOf("http://192.168.") === 0 || origin.indexOf("http://www.sportyuan.com") === 0 || origin.indexOf("http://www.dian-na.com") === 0) {
            //开发模式
            origin_result = origin;
        } else {
            //从白名单中进行匹配
            /*if (white_list_map[domain]) {
                origin_result = origin;
                req.headers["bus_id"] = white_list_map[domain];
            } else */
            console.log(domain)
            if (white_list_map[host]) {
                origin_result = origin;
                req.headers["bus_id"] = white_list_map[host];
            } else if (domain === "dotnar.com" || domain === "dian-na.com") {
                origin_result = origin;
                req.headers["bus_id"] = white_list_map[host];
            } else if (domain === "dev-dotnar.com") {
                origin_result = origin;
                req.headers["bus_id"] = white_list_map["d1.dev-dotnar.com"];
            } else if (domain.indexOf("shengyi8888.com") > -1) {
                origin_result = origin;
                req.headers["bus_id"] = "shengyi";
            } else if (!domain) {
                var state = req.query.state;
                if (typeof state === "string") {
                    var state_info = state.split("|");
                    console.log("WX state_info:", state_info);
                    if (state_info.length > 1) {
                        var bus_id = state_info.shift();
                        req.query.state = state_info.join("|");
                        req.headers["bus_id"] = bus_id;
                    }
                }
            }
            /* else {
                            req.headers["bus_id"] = "dotnar_d1";
                        }*/
        }
        //确保直接访问可以使用，比如支付宝完成支付直接访问api.dotnar.com时，能正常进行支付流程
        req.headers["bus_id"] || (req.headers["bus_id"] = "dotnar_d1");

        res.header("Access-Control-Allow-Credentials", true);
        res.header("Access-Control-Allow-Origin", origin_result);
        res.header("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS");
        res.header("Access-Control-Allow-Headers", "X-PINGOTHER, Set-Cookie, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version");
        //设定P3P规范
        res.header("P3P", "CP=IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA");
        console.log("访问者标志：", req.header("User-Agent"));
        next();
    }
    module.exports.white_list_map = white_list_map;
}());
